package com.wtgroup.demo.leetcode.q014_最长公共前缀;

/**
 * @author dafei
 * @version 0.1
 * @date 2021/3/30 10:08
 */
public class S_My {

    public static void main(String[] args) {
        // String[] strs = {"flower","flow","flight"};
        // String[] strs = {"dog","racecar","car"};
        String[] strs = {"a"};
        String ans = new S_My().longestCommonPrefix(strs);
        System.out.println(ans);
    }

    public String longestCommonPrefix(String[] strs) {
        if (strs.length==0) {
            return "";
        }
        String ans = strs[0];
        for (String str : strs) {
            ans = this.getCommonPrefix(str, ans);
            // 优化: 已经是空串, 没必要继续遍历了
            if (ans == "") {
                break;
            }
        }
        return ans;
    }

    private String getCommonPrefix(String a, String b) {
        int i = 0;
        int len = Math.min(a.length(), b.length());
        for (i = 0; i < len; i++) {
            if (a.charAt(i) != b.charAt(i)) {
                break;
            }
        }
        return a.substring(0, i);
    }
}
